<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form inline size="small" :model="from" ref="from" :label-position="labelPosition" label-width="100px">
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <el-form-item label="标题：">
                  <el-input v-model="from.title" placeholder="请输入标题" clearable class="selWidth" />
                </el-form-item>
                <el-form-item label="发布状态：">
                  <el-select v-model="from.sendStatus" placeholder="请选择" class="selWidth" clearable>
                    <el-option :value="0" label="未发布"></el-option>
                    <el-option :value="1" label="已发布"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6" class="text-right from">
                <el-form-item>
                  <el-button class="mr10" size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
                  <el-button class="mr10" size="small" icon="el-icon-refresh" @click="reset()">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="btn_bt">
          <el-button class="mr10" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="add()">新增</el-button>
          <el-button class="mr10" size="small" type="danger" icon="el-icon-delete" @click="allDel()">删除</el-button>
        </div>
      </div>
      <el-table border ref="table" v-loading="loading" :data="tableData.data" style="width: 100%" size="mini"
        @selection-change="onSelectTab" highlight-current-row>
        <el-table-column type="selection" width="100">
        </el-table-column>
        <el-table-column prop="id" label="ID" min-width="150" />
        <el-table-column prop="title" label="标题" min-width="100" />
        <el-table-column prop="msgType" label="通告对象" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.msgType == 'USER'">指定用户</span>
            <span v-if="scope.row.msgType == 'ALL'">全体用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" min-width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.priority == 1">低</span>
            <span v-if="scope.row.priority == 2">中</span>
            <span v-if="scope.row.priority == 3">高</span>
          </template>
        </el-table-column>
        <el-table-column prop="sendStatus" label="状态" min-width="100">
          <template slot-scope="scope">
            <el-button type="info" size="mini" v-if="scope.row.sendStatus == 0">未发布</el-button>
            <el-button type="primary" size="mini" v-if="scope.row.sendStatus == 1">已发布</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发布时间" min-width="150" />
        <el-table-column label="操作" min-width="150" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" v-if="scope.row.sendStatus == 0" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.sendStatus == 0" @click.native="handleRelease(scope.row)">发布</el-dropdown-item>
                <el-dropdown-item @click.native="handleDel(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[15, 30, 45, 60]" :page-size="from.limit" :current-page="from.page"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleSizeChange"
          @current-change="pageChange" />
      </div>
    </el-card>

    <el-dialog :title="ruleForm.id?'编辑':'新增'" :visible.sync="dialogVisible" width="1000px"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="120px">
        <el-form-item label="标题：" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="通告对象：" prop="msgType">
          <el-radio-group v-model="ruleForm.msgType">
            <el-radio :label="'USER'">指定用户</el-radio>
            <el-radio :label="'ALL'">全体用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级：" prop="priority">
          <el-radio-group v-model="ruleForm.priority">
            <el-radio :label="1">低</el-radio>
            <el-radio :label="2">中</el-radio>
            <el-radio :label="3">高</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="ruleForm.msgType == 'USER'" label="指定用户：" prop="userIds">
          <el-select style="width: 100%;" v-model="ruleForm.userIds" placeholder="请选择用户" multiple filterable remote reserve-keyword clearable
            :remote-method="loadUsers">
            <el-option v-for="item in users" :key="String(item.uid)" :label="item.nickname" :value="String(item.uid)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容：" prop="msgContent">
          <vue-ueditor-wrap v-model="ruleForm.msgContent" :config="myConfig" @beforeInit="addCustomDialog"
            style="width: 90%;"></vue-ueditor-wrap>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    annountCementList,
    annountCementDoReleaseData,
    annountCementDelete,
    annountCementQueryById,
    annountCementAdd,
    annountCementEdit
  } from '@/api/dataField'
  import {
    userListApi
  } from '@/api/user'
  import SettingMer from '@/utils/settingMer'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    name: 'notice',
    data() {
      const url = SettingMer.httpUrl + '/upload/image/0/file?ueditor=1&token=' + getToken()
      return {
        myConfig: {
          autoHeightEnabled: false, // 编辑器不自动被内容撑高
          initialFrameHeight: 500, // 初始容器高度
          initialFrameWidth: '100%', // 初始容器宽度
          elementPathEnabled: false,
          wordCount: false,
          enableAutoSave: false,
          UEDITOR_HOME_URL: '/UEditor/',
          'serverUrl': url,
          'imageUrl': url,
          'imageFieldName': 'file',
          imageUrlPrefix: '',
          'imageActionName': 'upfile',
          'imageMaxSize': 2048000,
          'imageAllowFiles': ['.png', '.jpg', '.jpeg', '.gif', '.bmp']
        },
        labelPosition: 'right',
        from: {
          title: '',
          sendStatus: '',
          page: 1,
          limit: 15,
        },
        loading: false,
        tableData: {
          data: [],
          total: 0
        },
        selection: [],
        dialogVisible: false,
        ruleForm: {
          id: '',
          title: '',
          msgType: '',
          userIds: [],
          msgContent: '',
        },
        users: [],
        currentPage: 1,
        pageSize: 15,
        rules: {
          title: [{
            required: true,
            message: '请填写标题',
            trigger: 'blur'
          }],
          priority: [{
            required: true,
            message: '请选择优先级',
            trigger: 'change'
          }],
          msgType: [{
            required: true,
            message: '请选择通告对象',
            trigger: 'change'
          }],
          msgContent: [{
            required: true,
            message: '请填写内容',
            trigger: 'blur'
          }],
        }
      }
    },
    mounted() {
      this.getlist()
    },
    methods: {
      // 添加自定义弹窗
      addCustomDialog(editorId) {
        window.UE.registerUI('test-dialog', function(editor, uiName) {
          // 创建 dialog
          const dialog = new window.UE.ui.Dialog({
            // 指定弹出层中页面的路径，这里只能支持页面，路径参考常见问题 2
            iframeUrl: '/setting/uploadPicture?field=dialog',
            // 需要指定当前的编辑器实例
            editor: editor,
            // 指定 dialog 的名字
            name: uiName,
            // dialog 的标题
            title: '上传图片',
            // 指定 dialog 的外围样式
            cssRules: 'width:1000px;height:620px;padding:20px;'
          })
          this.dialog = dialog
          var btn = new window.UE.ui.Button({
            name: 'dialog-button',
            title: '上传图片',
            cssRules: `background-image: url(@/assets/images/icons.png);background-position: -726px -77px;`,
            onclick: function() {
              // 渲染dialog
              dialog.render()
              dialog.open()
            }
          })
          return btn
        }, 37)
      },
      loadUsers(query) {
        if (query !== '') {
          this.currentPage = 1
          this.users = []
          this.getuserlist(query)
        } else {
          this.users = [];
        }
      },
      getuserlist(query) {
        let data = {
          page: this.currentPage,
          limit: this.pageSize,
          keywords: query
        }
        userListApi(data).then(res => {
          console.log('用户列表', res)
          this.users = this.users.concat(res.list)
        }).catch(err => {
          console.log(err)
        })
      },
      search() {
        this.from.page = 1
        this.from.limit = 15
        this.getlist()
      },
      reset() {
        this.from = {
          title: '',
          sendStatus: '',
          page: 1,
          limit: 15,
        }
        this.getlist()
      },
      getlist() {
        this.loading = true
        annountCementList(this.from).then(res => {
          console.log(res)
          this.tableData.data = res.list
          this.tableData.total = res.total
          this.loading = false
        }).catch(err => {
          console.log(err)
          this.loading = false
        })
      },
      add() {
        this.ruleForm = {
          id: '',
          title: '',
          msgType: '',
          priority: '',
          userIds: [],
          msgContent: '',
        }
        this.dialogVisible = true
      },
      close() {
        this.ruleForm = {
          id: '',
          title: '',
          msgType: '',
          priority: '',
          userIds: [],
          msgContent: '',
        }
        this.dialogVisible = false
      },
      submit() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.ruleForm.id) {
              console.log('编辑', this.ruleForm)
              let userIds = this.ruleForm.userIds.join()
              let data = {
                id: this.ruleForm.id,
                title: this.ruleForm.title,
                msgType: this.ruleForm.msgType,
                priority: this.ruleForm.priority,
                userIds: userIds,
                msgContent: this.ruleForm.msgContent,
              }
              annountCementEdit(data).then(res => {
                console.log(res)
                this.close()
                this.$message.success('编辑成功')
                this.getlist()
              }).catch(err => {
                console.log(err)
                this.$message.error(err)
              })
            } else {
              console.log('新增', this.ruleForm.userIds)
              let userIds = this.ruleForm.userIds.join()
              let data = {
                title: this.ruleForm.title,
                msgType: this.ruleForm.msgType,
                priority: this.ruleForm.priority,
                userIds: userIds,
                msgContent: this.ruleForm.msgContent,
              }
              annountCementAdd(data).then(res => {
                console.log(res)
                this.close()
                this.$message.success('新增成功')
                this.getlist()
              }).catch(err => {
                console.log(err)
                this.$message.error(err)
              })
            }
          } else {
            this.$message.error('请填写完整信息')
          }
        });
      },
      // 选择
      onSelectTab(selection) {
        this.selection = []
        selection.forEach(item => {
          this.selection.push(item.id)
        })
        console.log(this.selection)
      },
      allDel() {
        if (this.selection.length == 0) {
          return this.$message.error('至少选择一项')
        }
        console.log(this.selection)
        this.$confirm('确认删除？')
          .then(_ => {
            annountCementDelete(this.selection).then(res => {
              console.log(res)
              this.$message.success('删除成功')
              this.getlist()
            }).catch(err => {
              console.log(err)
              this.$message.error(err)
            })
          })
          .catch(_ => {});
      },
      handleEdit(row) {
        annountCementQueryById(row).then(res => {
          console.log('系统通告详情', res)
          this.ruleForm = {
            id: res.id,
            title: res.title,
            msgType: res.msgType,
            priority: res.priority,
            userIds: res.userIds?res.userIds.split(","):[],
            msgContent: res.msgContent,
          }
          this.users = res.userList
          console.log(this.ruleForm,this.users)
          this.dialogVisible = true
        }).catch(err => {
          console.log(err)
          this.$message.error(err)
        })
      },
      handleRelease(row) {
        this.$confirm('确认发布？')
          .then(_ => {
            console.log('发布', row)
            annountCementDoReleaseData(row.id).then(res => {
              console.log(res)
              this.$message.success('发布成功')
              this.getlist()
            }).catch(err => {
              console.log(err)
              this.$message.error(err)
            })
          })
          .catch(_ => {});
      },
      handleDel(row) {
        this.$confirm('确认删除？')
          .then(_ => {
            console.log('删除', row)
            annountCementDelete([row.id]).then(res => {
              console.log(res)
              this.$message.success('删除成功')
              this.getlist()
            }).catch(err => {
              console.log(err)
              this.$message.error(err)
            })
          })
          .catch(_ => {});
      },
      pageChange(page) {
        this.from.page = page
        this.getlist()
      },
      handleSizeChange(val) {
        this.from.limit = val
        this.getlist()
      }
    }
  }
</script>

<style scoped lang="scss">
  .btn_bt {
    border-top: 1px dashed #ccc;
    padding-top: 20px;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
